import { baseGetPath } from "@/app/(dashboard)/common/config/baseURL"
import { serverFileBaseUrl } from "@/app/api/util/config"
import { getAbsPath } from "@/app/api/util/other"
import 'server-only'
import dayjs from "dayjs"
/**文件名中，用户与md5的分隔符 */
const separator = '_'

/**获得文件的前缀 `${userId}_${md5}`  */
const getFilePrefix = (userId: string, md5: string) => {
    return `${userId}${separator}${md5}`
}
/**获得完整文件名
 * @param userId 用户工号
 * @param md5 md5
 * @param suffix 后缀
 * @returns `${userId}_${md5}${suffix}`
 */
export const getFileName = (userId: string, md5: string, suffix?: string) => {
    if (!suffix) {
        return `${getFilePrefix(userId, md5)}`
    }
    if (!suffix.startsWith('.')) suffix = '.' + suffix
    return `${getFilePrefix(userId, md5)}${suffix}`
}
/**获得临时文件的目录 `/temp/${userId}_${md5}/`  */
export const getTempDir = (userId: string, md5: string) => {
    return getAbsPath(`/temp/${getFilePrefix(userId, md5)}/`)
}
/**获得临时文件路径 */
export const getTempFilePath = (userId: string, md5: string, index: string | number) => {
    return `${getTempDir(userId, md5)}/${index}`
}
/**获得服务器路径和外部路径公用的部分 `/${path}/${getFileName(userId, md5, suffix)}`  */
export const getCommonPath = (userId: string, md5: string, suffix: string, path: string) => {
    return `/${path}/${getFileName(userId, md5, suffix)}`
}

/**获得服务器路径和外部路径公用的部分，自定义服务器路径名后面的文件名(ai换脸模块专用，特殊需求)  */
export const getCommonPathByOwnFileName = (userId: string, md5: string, ownFileName: string, suffix: string, path: string) => {
    if (!suffix.startsWith('.')) suffix = '.' + suffix
    if (ownFileName === 'posture') {
        return `/${path}/${getCurrentTime()}/posture/${getFileName(userId, md5)}_${ownFileName}${suffix}`
    }
    return `/${path}/${getCurrentTime()}/anchor_face/${getFileName(userId, md5)}_${ownFileName}${suffix}`
}
/**获取当前年月 */
const getCurrentTime = () => {
    const timeStamp = Date.now()
    const date = new Date(timeStamp)
    return `${date.getFullYear()}_${date.getMonth() + 1}`
}


/**获得服务器路径 （实际上就是拼接了 /data3/aigc/datasets/ ） */
export const getServerPath = (originPath: string) => {
    return serverFileBaseUrl + originPath;
}
/**获得外部访问的路径 （实际上就是拼接了 https://aigc.yy.com/public_resource/get_data ） */
export const getPublicPath = (originPath: string) => {
    return baseGetPath + originPath
}
/**获得路径的上传用户 */
export const getFileUser = (filePath: string) => {
    // 目标：拆解字符串"https://aigc.yy.com/public_resource/get_data//other/JZ8322_7950ffb27039e6cc08921b32dbbea59a.svg"
    // 得到userid
    const arr = filePath.split('/')
    const name = arr[arr.length - 1]
    return name.split(separator)[0]
}
/**公网路径转服务器存储路径 */
export const publicToServerPath = (publicPath: string) => {
    if (!publicPath.startsWith(baseGetPath)) throw '路径不符合规范'
    const commonPath = publicPath.replace(baseGetPath, '')
    return getServerPath(commonPath)
}
